package com.shaozi.nc.web.action;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shaozi.lib.core.ActionRetBean;
import com.shaozi.nc.data.model.OrgPushMsgModel;
import com.shaozi.nc.manage.OrgPushMsgManage;
import com.shaozi.nc.web.action.base.BaseActionImpl;
import com.shaozi.nc.web.beans.AddPushMsgReqBean;
import com.shaozi.nc.web.beans.DelPushMsgReqBean;
import com.shaozi.nc.web.beans.PushMsgAtTimeReqBean;
import com.shaozi.nc.web.biz.PushMsgBiz;
import com.shaozi.utils.common.BeanUtils;

@Controller
@RequestMapping(value = "/pushMsg")
public class PushMsgAction extends BaseActionImpl {

	private static final Logger logger = Logger.getLogger(PushMsgAction.class);

	@Autowired
	private PushMsgBiz bizPushMsg;

	public PushMsgAction() {

	}

	/**
	 * 
	 * @param companyId
	 *            :公司ID<br>
	 * @param userId
	 *            : 推送对方的用户ID <br>
	 * @param sourceId
	 *            : 来源的ID，如任务模块，该值是taskId<br>
	 * @param sourceType
	 *            :来源类型：1:IM消息提醒 ，3：定时写工作汇报提醒 4:设置任务提醒 ,5:上级提醒写工作汇报<br>
	 * @param atTime
	 *            :执行时间，0立即执行 <br>
	 * @param title
	 *            ： 显示标题 <br>
	 * @param content
	 *            :显示内容
	 * 
	 * @param callbackUrl
	 *            回调的URL
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = { "/oa/addAtTime",
			"/oa/editAtTime" }, method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ActionRetBean addPushMsgAtTime(HttpServletRequest req, HttpServletResponse res,
			@RequestBody PushMsgAtTimeReqBean reqBean) throws UnsupportedEncodingException {
		ActionRetBean ret = new ActionRetBean();
		if ((reqBean.getAtTime() == null) || (reqBean.getAtTime() == 0l)) {
			ret.setCode(-1);
			return ret;
		}
		if (StringUtils.isEmpty(reqBean.getCompanyId())) {
			ret.setCode(-1);
			return ret;
		}
		if ((reqBean.getAtTime() != -1) && (reqBean.getAtTime() < System.currentTimeMillis())) {
			ret.setCode(-1);
			return ret;
		}

		Long expireTime = 0l;
		Integer repeatCount = 0;
		Integer intervalTimeSec = null;
		boolean isBadge = false;
		Integer subPushIntervalSec = null;
		Integer subPushRepeatCount = null;

		bizPushMsg.addPushMsg(ret, reqBean.getCompanyId(), reqBean.getUserId(), reqBean.getSourceId(),
				reqBean.getAtTime(), reqBean.getSourceType(), expireTime, repeatCount, intervalTimeSec, isBadge,
				reqBean.getTitle(), reqBean.getContent(), subPushIntervalSec, subPushRepeatCount);
		return ret;
	}

	@RequestMapping(value = { "/oa/delAtTime" }, method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ActionRetBean delPushMsg(HttpServletRequest req, HttpServletResponse res,
			@RequestBody DelPushMsgReqBean reqBean) {
		ActionRetBean ret = new ActionRetBean();
		if (StringUtils.isEmpty(reqBean.getCompanyId())) {
			ret.setCode(-1);
			return ret;
		}
		bizPushMsg.delPushMsg(ret, reqBean.getCompanyId(), reqBean.getUserId(), reqBean.getSourceId(),
				reqBean.getSourceType());
		return ret;
	}

	/**
	 * 
	 * @param req
	 * @param res
	 * @param compId
	 * @param pushSec
	 *            秒
	 * @param pushMin
	 *            分
	 * @param pushHour
	 *            时
	 * @param day
	 * @param month
	 * @param week
	 * @param year
	 * @param sourceType
	 *            1: im, 2:oa
	 * @param expireTime
	 * @param repeatCount
	 * @param intervalTimeSec
	 * @param isBadge
	 * @param title
	 * @param content
	 * @param subPushIntervalSec
	 * @param subPushRepeatCount
	 * @return
	 */
	@RequestMapping(value = "/oa/add", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ActionRetBean addPushMsg(HttpServletRequest req, HttpServletResponse res,
			@RequestBody AddPushMsgReqBean reqBean) {
		ActionRetBean ret = new ActionRetBean();
		bizPushMsg.addPushMsg(ret, reqBean);
		return ret;
	}

	@RequestMapping(value = { "/oa/addOrgPush",
			"/oa/editOrgPush" }, method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ActionRetBean addOrgPushMsg(HttpServletRequest req, HttpServletResponse res,
			@RequestBody List<OrgPushMsgModel> models) {
		ActionRetBean ret = new ActionRetBean();
		OrgPushMsgManage orgMgr = (OrgPushMsgManage) BeanUtils.getBean("orgPushMsgMgr");
		// System.out.println(models);
		int count = 0;
		for (OrgPushMsgModel m : models) {
			if (!validOrgPushModel(m))
				continue;
			orgMgr.upsertOrgPushMsg(m.getCompId(), m);
			count++;
		}
		ret.setCode(0);
		return ret;
	}

	private boolean validOrgPushModel(OrgPushMsgModel m) {
		if (m.getLevelType() == null)
			return false;
		if (m.getSourceType() == null)
			return false;
		if (m.getCompId() == null)
			return false;
		if (m.getPushRegex() == null)
			return false;
		String[] expresses = m.getPushRegex().split(" ");
		if (expresses.length < 6)
			return false;

		if (m.getTitle() == null)
			return false;
		if (m.getContent() == null)
			return false;
		if (!CronExpression.isValidExpression(m.getPushRegex())) {
			logger.info("valid cron express fail:" + m.getPushRegex());
			return false;
		}
		return true;
	}

}
